/*
 * Copyright (c) 2012 Sean Connelly
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var assert = require('../assert.js').init();
var common = require('../../src/js/common.js');
var path = require('path');
var fs = require('fs');
var txs = require('../../src/js/text-stream.js');
var lxr = require('../../src/js/lex-rho.js');
var psr = require('../../src/js/parse-rho.js');

function collapseTree(str)
{
	var ast = psr.parse(lxr.lex(txs.create(str)));
	console.log(JSON.stringify(ast.dumpAst(false)));
	return ast;
}

function loadRhoFile(test_dir, file)
{
	var c = fs.readFileSync(path.resolve(test_dir, file), 'utf8');
	assert.that(file + ' loaded', c.length > 0);
	return c;
}

function loadJsonFile(test_dir, file)
{
	var c = fs.readFileSync(path.resolve(test_dir, file), 'utf8');
	assert.that(file + ' loaded', c.length > 0);
	var obj = (new Function('return ' + c + ';'))();
	assert.that(file + ' parsed', typeof obj === 'object');
	return obj;
}

function testFile(test_dir, file)
{
	var ast = psr.parse(lxr.lex(txs.create(loadRhoFile(test_dir, file + '.rho')))).dumpAst();
	//fs.writeFileSync(path.resolve(test_dir, file + '.out.json'), common.niceJson(ast), 'utf8');
	var target_obj = loadJsonFile(test_dir, file + '.json');
	assert.that(file + ' matches target object', common.objectsMatch(ast, target_obj));
}

exports.run = function(root_dir, test_dir, test_name) {
		for (var i = 1; i <= 15; i++)
			testFile(test_dir, 'test' + i);
		return assert.result();
	};
